/**
 * Created by vincent on 2016/12/5.
 */
moduleMain.controller('HomepageController', function ($stateParams, LanguageService, GeneralResource, LoadingService, $scope, $rootScope, $state, ConstantService, DashboardResource) {
    initPage($scope);

    var myColors = ["#33414E", "#8DCA35", "#00BFDD", "#FF702A", "#DA3610",
        "#80CDC2", "#A6D969", "#D9EF8B", "#FFFF99", "#F7EC37", "#F46D43",
        "#E08215", "#D73026", "#A12235", "#8C510A", "#14514B", "#4D9220",
        "#542688", "#4575B4", "#74ACD1", "#B8E1DE", "#FEE0B6", "#FDB863",
        "#C51B7D", "#DE77AE", "#EDD3F2"];
    d3.scale.myColors = function () {
        return d3.scale.ordinal().range(myColors);
    };

    $scope.reportSpaceTypes = [
        {key: 'DAILY', value: LanguageService.language('日趋势')},
        {key: 'WEEKLY', value: LanguageService.language('周趋势')},
        {key: 'MONTHLY', value: LanguageService.language('月趋势')}
    ];

    $scope.$on("$viewContentLoaded", function () {

        ConstantService.clearState();
        // try {
        templatePlugins.ready();
        templateActions.onload();
        !templateActions.load && templateActions.ready();
        templateDemoDashboard.ready();
        // }catch (e){
        //     console.log(e);
        // }
        $scope.user = ConstantService.getItem('user');

        if($stateParams.organizationClientId){
            $scope.currentOrganizationClientId = $stateParams.organizationClientId;
        }else{
            $scope.currentOrganizationClientId = $scope.user.createOrgId;
        }

        $scope.loadDashboard(function (result) {
            $scope.userTotal(result.data);
        });
        //DAILY
        $scope.selectedPvReportSpaceTypes = $scope.reportSpaceTypes[0].key;
        $scope.initReport();
        $scope.loadDataPvReport();
        // $scope.loadDataPvReport('DAILY');
        $scope.selectedUserTotalPvSpaceTypes = $scope.reportSpaceTypes[0].key;
        $scope.initChatUserTotalPvTotal();
        $scope.loadDataChatUserTotalPvTotal();
        // $scope.loadDataChatUserTotalPvTotal('DAILY');
    });


    $scope.toPercent = function (num, total) {
        if (num == 0 || total == 0) {
            return 0;
        }
        return parseInt(Math.round(num / total * 10000)) / 100.00;// 小数点后两位百分比
    }

    $scope.formatNumber = function (number) {
        if (!number || number == 0) {
            return 0;
        }
        return number;// 小数点后两位百分比
    }

    //================================================================================================================================================
    //================================================================================================================================================

    $scope.selectedUserTotalPvSpaceTypes = $scope.reportSpaceTypes[0].key;

    var userTotalPvStart = moment().add(-12, 'days')._d;
    var userTotalPvEnd = new Date();

    $scope.changeUserTotalPvSpaceTypes = function () {
        $scope.loadDataChatUserTotalPvTotal();
    }

    $scope.initChatUserTotalPvTotal = function () {

        $("#report-range-userTotal-pvTotal").daterangepicker({
            // ranges: ranges,
            opens: 'left',
            buttonClasses: ['btn btn-default'],
            // applyClass: 'btn-small btn-primary',
            // cancelClass: 'btn-small',
            // format: 'MM.DD.YYYY'
            // separator: ' to ',
            startDate: moment().add(-12, 'days'),
            endDate: moment()
        }, function (start, end) {
            userTotalPvStart = start._d;
            userTotalPvEnd = end._d;
            $scope.loadDataChatUserTotalPvTotal();
            // $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
        });
    }

    //templateSetting.ready();
    $scope.loadDataChatUserTotalPvTotal = function () {
        var startTime = userTotalPvStart.getTime();
        var endTime = userTotalPvEnd.getTime();
        DashboardResource.chatUserTotalPvTotal({type: $scope.selectedUserTotalPvSpaceTypes, startTime: startTime, endTime: endTime, organizationClientId: $scope.currentOrganizationClientId}, {}, function (result) {
            var userTotals = new Array();
            var useFrequencies = new Array();
            for (var i = 0; i < result.data.details.length; i++) {
                var userTotal = new Array();
                userTotal.push(result.data.details[i].time);
                userTotal.push($scope.formatNumber(result.data.details[i].countLoginUser));
                // userTotal.push(parseInt(10*Math.random()));
                userTotals.push(userTotal);

                var useFrequency = new Array();
                useFrequency.push(result.data.details[i].time);
                useFrequency.push($scope.toPercent(result.data.details[i].countLoginUser, result.data.details[i].countUserTotal));
                // useFrequency.push(parseInt(10*Math.random()));
                useFrequencies.push(useFrequency);
            }

            var data = new Array();
            var pvTotalBean = {
                "key": LanguageService.language('人数'),
                "bar": true,
                // "color": "#E1E3E8",
                "color": "#626c91",
                "values": userTotals
            };
            data.push(pvTotalBean);var data = new Array();
            var pvTotalBean = {
                "key": LanguageService.language('人数'),
                "bar": true,
                // "color": "#E1E3E8",
                "color": "#626c91",
                "values": userTotals
            };
            data.push(pvTotalBean);
            // var userTotalBean = {
            // var userTotalBean = {
            //     "key": LanguageService.language('使用率'),
            //     "color": "#66CCFF",
            //     "values": useFrequencies
            // }
            // data.push(userTotalBean);

            $("#chart-userTotal-pvTotal-div").remove();
            var d = $('<div id="chart-userTotal-pvTotal-div"><svg></svg></div>');
            $("#chart-userTotal-pvTotal").append(d);

            chatUserTotalPvTotal(data);
        });
    }


    var chatUserTotalPvTotal = function (data) {
        nv.addGraph(function () {
            var chart = nv.models.linePlusBarChart().margin({
                top: 10,
                right: 40,
                bottom: 20,
                left: 30
            })
            //We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
                .x(function (d, i) {
                    return i;
                }).y(function (d, i) {
                    return d[1];
                }).color(d3.scale.myColors().range()).showLegend(false);
            ;
            // chart.xAxis.tickFormat(function (d) {
            //     var dx = data[0].values[d] && data[0].values[d][0] || 0;
            //     return d3.time.format('%x')(new Date(dx));
            // });
            chart.xAxis.tickFormat(function (d) {
                return data[0].values[d] && data[0].values[d][0] || 0;
                // return d3.time.format('%x')(new Date(dx));
            });
            chart.y1Axis.tickFormat(function (d) {
                return d3.format(',f')(d);
            });
            // chart.y1Axis.tickFormat(function (d) {
            //     return d;
            // });
            chart.y2Axis.tickFormat(function (d) {
                return d + "%";
            });
            chart.bars.forceY([0]);
            d3.select('#chart-userTotal-pvTotal svg').datum(data).transition().duration(0).call(chart);
            nv.utils.windowResize(chart.update);
            return chart;
        });


    }
    //================================================================================================================================================
    //================================================================================================================================================

    $scope.loadDashboard = function (success) {
        // //LoadingService.show();
        DashboardResource.load({organizationClientId: $scope.currentOrganizationClientId}, {}, function (result) {
            $scope.dashboard = result.data;
            if (StringUtils.defaultEmpty($scope.dashboard.userTotal, 0) == 0) {
                $scope.dashboard.userProportion = 0;
            } else {
                $scope.dashboard.monthUserTotal = StringUtils.defaultEmpty($scope.dashboard.returnUserTotal, 0) + StringUtils.defaultEmpty($scope.dashboard.newUserTotal, 0);
                $scope.dashboard.userProportion = $scope.dashboard.monthUserTotal / StringUtils.defaultEmpty($scope.dashboard.userTotal, 0);
                $scope.dashboard.userProportion = parseInt($scope.dashboard.userProportion * 100);
            }
            // //LoadingService.hide();
            if (success) {
                success(result);
            }
        }, function () {
            // //LoadingService.hide();
        })
    }

    $scope.userTotal = function (dashboard) {
        //userProportion
        // dashboard.userProportion = (dashboard.returnUserTotal + dashboard.newUserTotal) / dashboard.userTotal * 100;
        //
        //
        var datas = new Array();
        datas.push({label: LanguageService.language('回流用户'), value: dashboard.returnUserTotal});
        datas.push({label: LanguageService.language('新增用户'), value: dashboard.newUserTotal});
        Morris.Donut({
            backgroundColor: '#66CCFF',
            element: 'dashboard-newUserTotal-returnUserTotal',
            data: datas,
            colors: ["#FFFFFF", "#626c91"],
            resize: true
        });

    }
    //================================================================================================================================================
    //================================================================================================================================================

    $scope.selectedPvReportSpaceTypes = $scope.reportSpaceTypes[0].key;

    var pvReportStart = moment().add(-12, 'days')._d;
    var pvReportEnd = new Date();

    $scope.changePvReportSpaceTypes = function () {
        $scope.loadDataPvReport();
    }

    $scope.initReport = function () {
        $("#report-range-pv").daterangepicker({
            opens: 'left',
            buttonClasses: ['btn btn-default'],
            // applyClass: 'btn-small btn-primary',
            // cancelClass: 'btn-small',
            // format: 'MM.DD.YYYY'
            // separator: ' to ',
            startDate: moment().add(-12, 'days'),
            endDate: moment()
        }, function (start, end) {
            pvReportStart = start._d;
            pvReportEnd = end._d;
            $scope.loadDataPvReport();
            // $scope.loadDataPvReport(start, end);
            // $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
        });
    }

    $scope.loadDataPvReport = function () {
        var startTime = pvReportStart.getTime();
        var endTime = pvReportEnd.getTime();
        DashboardResource.pvReport({type: $scope.selectedPvReportSpaceTypes, startTime: startTime, endTime: endTime, organizationClientId: $scope.currentOrganizationClientId}, {}, function (result) {
            $("#dashboard-pv-report").remove();
            var d = $('<div class="chart-holder" id="dashboard-pv-report" style="height: 200px;"></div>');
            $("#dashboard-pv-report-div").append(d);

            /* Line dashboard chart */
            Morris.Line({
                element: 'dashboard-pv-report',
                data: result.data,
                xkey: 'time',
                ykeys: ['total', 'totalTime'],
                labels: [LanguageService.language('次数'), LanguageService.language('时长')],
                // resize: true,
                hideHover: true,
                parseTime: false,
                xLabels: 'day',
                gridTextSize: '10px',
                // lineColors: ["#E1E3E8", "#66CCFF"],
                lineColors: ["#626c91", "#66CCFF"],
                gridLineColor: '#E5E5E5'
            });
        }, function () {
            //LoadingService.hide();
        })
    }

    //================================================================================================================================================

    $scope.openLearningMapInfo = function(){
        $state.go('sz.dashboardLearningMapDetailReport', {
            organizationClientId: $scope.currentOrganizationClientId
        })
    }
});